import { Empty } from 'antd';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import React, { useCallback, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ChartType, ComposedChartType, onCardClick } from '../libs/chartCommon';
import { refineFilterCondition } from '../libs/filterCommon';
import useCustomQuery from '../libs/hooks/useCustomQuery';
import useFilterMeta from '../libs/hooks/useFilterMeta';
import useSaLogging, { eventMap } from '../libs/hooks/useSaLogging';
import { chartAction, chartState } from '../libs/slices/chartManagerSlice';
import { selectFilter } from '../libs/slices/filterSlice';

const ChartSelection = dynamic(() => import('../components/ChartSelection'));
const CardTemplate = dynamic(() => import('../components/templates/CardTemplate'));

export interface DashboardCardWrapperProps {
  key: string;
  title: string;
  chartType: ChartType;
  url: string;
  dimensions: string[];
  xlabel: string;
  metrics: string[];
  dataLimit: number;
  yAxisPrefix?: string;
  composedChartMapping?: { [key: string]: ComposedChartType };
}

const DashboardCardWrapper = ({
  title,
  chartType,
  url,
  dimensions,
  xlabel,
  metrics,
  dataLimit,
  yAxisPrefix,
  composedChartMapping,
}: DashboardCardWrapperProps) => {
  const { chartList } = useSelector(chartState);
  const dispatch = useDispatch();
  const selectedFilter = useSelector(selectFilter);
  const router = useRouter();
  const { catalog } = useFilterMeta();
  const { saEvent } = useSaLogging();

  const condition = useMemo(() => {
    return refineFilterCondition(selectedFilter, catalog);
  }, [selectedFilter]);

  const dataFilter = useMemo(
    () => ({
      metrics,
      ...condition,
      dimensions,
      dataLimit,
    }),
    [metrics, condition, dimensions],
  );
  const { data, isLoading } = useCustomQuery({
    queryName: title,
    url,
    filter: dataFilter,
  });

  const onClick = useCallback(
    (event: React.MouseEvent<HTMLElement>) => {
      const productType = catalog;
      const target = event.target as HTMLInputElement;
      if (target.matches('#RemoveBtn svg, #RemoveBtn path')) {
        const title =
          event.currentTarget.querySelector('.ant-card-head-title')?.textContent;
        dispatch(chartAction.removeChart({ chartName: title, productType }));
        saEvent(eventMap.CARD_REMOVE, [
          { key: 'title', value: `${productType}_${title}` },
        ]);
      } else if (target.matches('#EnterPageBtn svg, #EnterPageBtn path')) {
        const title: string =
          event.currentTarget.querySelector('.ant-card-head-title')!.textContent!;
        const targetRoute = `/${productType}${
          chartList[productType].filter(chart => chart.name === title)[0].uri
        }`;
        router.push(targetRoute);
        saEvent(eventMap.CARD_ENTER, [
          { key: 'title', value: `${productType}_${title}` },
        ]);
      } else onCardClick(event, data, saEvent, productType);
    },
    [data],
  );
  const chartComponent = useMemo(() => {
    if (!isLoading && !data) return <Empty />;
    if (!isLoading && data) {
      return (
        <ChartSelection
          data={data}
          xlabel={xlabel}
          height="100%"
          chartType={chartType}
          metrics={metrics}
          yscroll={300}
          stackedLabelPrefix={yAxisPrefix}
          composedChartMapping={composedChartMapping}
          pageSizeOptions={['10', '30']}
          existTotal={false}
        />
      );
    }
    return null;
  }, [data, isLoading, chartType]);

  return (
    <CardTemplate
      isdashboard={true}
      title={title}
      content={chartComponent}
      onClick={onClick}
      showSubfilter={false}
      loading={isLoading}
    />
  );
};

export default DashboardCardWrapper;
